//
//  PreferenceController.m
//  ABlip
//
//  Created by dawid on 08-12-21.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "PreferenceController.h"
#import "AppController.h"
#import "AGKeychain.h"

NSString* const ABL_Transparency = @"ABLTransparency";
NSString* const ABL_TransparencyChangedNotification = @"ABLTransparencyChanged";
NSString* const ABL_MaxMsgShow=@"ABLMaxMsgShow";
NSString* const ABL_RefreshInterval = @"ABLRefreshInterval";
NSString* const ABL_LoginString = @"ABLLoginString";
NSString* const ABL_LastUpdateId = @"ABLLastUpdateId";
NSString* const ABL_AlwaysOnTop = @"ABLAlwaysOnTop";
NSString* const ABL_UpdatePreferences = @"ABLUpdatePreferences";
NSString* const ABL_SendMessageNotification = @"ABLSendMessageNotification";
NSString* const ABL_HotKeyNotification = @"ABLHotKeyPressed";
NSString* const ABL_HideAfterSendMsg = @"ABLHideAfterSend";
NSString* const ABL_HideGrowl = @"ABLHideGrowl";
NSString* const ABL_HideIconBadge = @"ABLHideIconBadge";
NSString* const ABL_ShowYoutube = @"ABLShowYoutube";

NSString* const ABL_ErrorMessageNotification= @"ABLErrorMessageNotification";
NSString* const ABL_QuoteClickedNotification= @"ABLQuoteClickedNotification";
NSString* const ABL_DeleteMessageClickedNotification= @"ABLDeleteMessageClickedNotification";
NSString* const ABL_CommandPlusNotification= @"ABLCommandPlusNotification";
NSString* const ABL_CommandMinusNotification= @"ABLCommandMinusNotification";

#define MAX_MSG_VISIBLE 250
#define MIN_MSG_VISIBLE 10
#define MAX_TIME_INTERVAL 360
#define MIN_TIME_INTERVAL 5

@implementation PreferenceController
@synthesize transparency;
@synthesize maxMsgShow;
@synthesize refreshInterval;
@synthesize alwaysOnTop;
@synthesize hideAfterSendMsg;
@synthesize hideGrowl;
-(id)init
{
	if (![super initWithWindowNibName:@"Preferences"])
		return nil;
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSNumber *number = [defaults objectForKey:ABL_Transparency];
	transparency = [number floatValue];
	number = [defaults objectForKey:ABL_MaxMsgShow];
	[self setMaxMsgShow:[number intValue]];
	number = [defaults objectForKey:ABL_AlwaysOnTop];
	alwaysOnTop = [number intValue];
	number = [defaults objectForKey:ABL_RefreshInterval];
	refreshInterval = [number intValue];
	number = [defaults objectForKey:ABL_HideAfterSendMsg];
	hideAfterSendMsg = [number intValue];
	number = [defaults objectForKey:ABL_HideGrowl];
	hideGrowl = [number intValue];
	number = [defaults objectForKey:ABL_HideIconBadge];
	hideIconBadge = [number intValue];
	number = [defaults objectForKey:ABL_ShowYoutube];
	showYoutube = [number intValue];
	
	return self;
}
-(void) windowDidLoad
{

}
-(void)awakeFromNib
{
	[maxMsgBox addItemsWithObjectValues:[NSArray arrayWithObjects:@"10",@"50", @"100", nil]];
	[refreshTimeBox addItemsWithObjectValues:[NSArray arrayWithObjects:@"10",@"30", @"60", nil]];
	[transparencySlider setFloatValue:transparency];
	[alwaysOnTopCheckBox setState:alwaysOnTop];
	[hideAfterSendCheckBox setState:hideAfterSendMsg];
	[userField setStringValue:[[AppController shared] userLogin] ];
	[passField setStringValue:[[AppController shared] userPassword] ];
	[hideGrowlCheckBox setState:hideGrowl];
	[hideIconBadgeCheckBox setState:hideIconBadge];
	[showYoutubeCheckBox setState:showYoutube];
}

-(void)setMaxMsgShow:(int)maxCount
{

	if (maxCount < MIN_MSG_VISIBLE){
		[maxMsgBox setIntValue:MIN_MSG_VISIBLE];
	} else if( maxCount > MAX_MSG_VISIBLE){
		//[self displayAlertWithMessageText:[NSString stringWithFormat: @"Wartość musi się znajdować pomiędzy: %d - %d", MIN_MSG_VISIBLE, MAX_MSG_VISIBLE]];
		[maxMsgBox setIntValue:MAX_MSG_VISIBLE];
	} else{
		maxMsgShow = maxCount;
		[maxMsgBox setIntValue:maxMsgShow];
	}
	
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:[NSNumber numberWithInt:maxMsgShow] forKey:ABL_MaxMsgShow];
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc postNotificationName:ABL_UpdatePreferences object:self];
	
}
-(void)setRefreshInterval:(int)value
{
	if (value < MIN_TIME_INTERVAL){
		[refreshTimeBox setIntValue:MIN_TIME_INTERVAL];
	}else if (value > MAX_TIME_INTERVAL){
		//[self displayAlertWithMessageText:[NSString stringWithFormat: @"Wartość musi się znajdować pomiędzy: %d - %d", MIN_TIME_INTERVAL, MAX_TIME_INTERVAL]];
		[refreshTimeBox setIntValue:MAX_TIME_INTERVAL];
	}else {
		refreshInterval = value;
		[refreshTimeBox setIntValue:refreshInterval];
	}
	
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:[NSNumber numberWithInt:refreshInterval] forKey:ABL_RefreshInterval];
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc postNotificationName:ABL_UpdatePreferences object:self];
	
}
-(void )setTransparency:(float)value
{
	transparency = value;
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:[NSNumber numberWithFloat:transparency] forKey:ABL_Transparency];
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc postNotificationName:ABL_TransparencyChangedNotification object:self];
}
-(void)setAlwaysOnTop:(int)value
{
	alwaysOnTop = value;
	[hideAfterSendCheckBox setEnabled:1-value];
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:[NSNumber numberWithInt:alwaysOnTop] forKey:ABL_AlwaysOnTop];
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc postNotificationName:ABL_UpdatePreferences object:self];
}
-(void)setHideAfterSendMsg:(int)value
{

	hideAfterSendMsg = value;
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:[NSNumber numberWithInt: hideAfterSendMsg] forKey:ABL_HideAfterSendMsg];
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc postNotificationName:ABL_UpdatePreferences object:self];
}
-(void)setHideGrowl:(int)value
{

	hideGrowl = value;
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:[NSNumber numberWithInt: hideGrowl] forKey:ABL_HideGrowl];
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc postNotificationName:ABL_UpdatePreferences object:self];
}
-(void)setHideIconBadge:(int)value
{
	hideIconBadge = value;
#ifdef __DEBUG__

//	NSLog(@"preHide = %d", hideIconBadge);

#endif
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:[NSNumber numberWithInt: hideIconBadge] forKey:ABL_HideIconBadge];
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc postNotificationName:ABL_UpdatePreferences object:self];
}
-(void)setShowYoutube:(int)value
{
	showYoutube = value;
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:[NSNumber numberWithInt:showYoutube] forKey:ABL_ShowYoutube];
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc postNotificationName:ABL_UpdatePreferences object:self];
}
-(IBAction)sliderChangeValue:(id)sender
{
	[self setTransparency:[transparencySlider floatValue]];
}
-(IBAction) resetPreferences:(id)sender
{	
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	
	[defaults setObject:[NSNumber numberWithFloat:0] forKey:ABL_Transparency];
	[defaults setObject:[NSNumber numberWithInt:50] forKey:ABL_MaxMsgShow];
	[defaults setObject:[NSNumber numberWithInt:30] forKey:ABL_RefreshInterval];
	[self setTransparency:0];
	[self setMaxMsgShow:50];
	[self setRefreshInterval:30];
	[self setAlwaysOnTop:0];
	[self setHideAfterSendMsg:1];
	
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc postNotificationName:ABL_UpdatePreferences object:self];
}

-(IBAction)changeLoginPasword:(id)sender
{
	
}
-(IBAction)trySaveToKeyChain:(id)sender
{
	

	NSString *log = [userField stringValue];
	NSString *passwd = [passField stringValue];
	
	if ([log isEqualToString:@""] || [passwd isEqualToString:@""] ){
#ifdef __DEBUG__

		NSLog(@"Login i/lub haslo nie moga byc puste");

#endif
		
		
	
	}else {

		[self modifyItemFromKeychain:log password:passwd];
		if ([log isEqualToString: [[AppController shared] userLogin] ] == NO){
			[AGKeychain deleteKeychainItem:KeyChainItemName 
							  withItemKind:KeyChainItemKind 
							   forUsername:[[AppController shared] userLogin]];
		}
		NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
		[defaults setObject:log forKey:ABL_LoginString];
		[[AppController shared] setUserLogin:log ];
		[[AppController shared] setUserPassword:[self getPasswordFromKeychainForLogin:log]];
	}
	
}
-(void)modifyItemFromKeychain:(NSString*)newLogin password:(NSString*)passwd
{
	
	
	BOOL doesItemExisit = [AGKeychain checkForExistanceOfKeychainItem:KeyChainItemName
														 withItemKind:KeyChainItemKind 
														  forUsername:newLogin ];							
	NSString *passwdToEncode  = [NSString stringWithFormat:@"%@:%@", newLogin, passwd];
	NSData *passwdData = [passwdToEncode dataUsingEncoding:NSUTF8StringEncoding];
	passwdToEncode = [passwdData encodeBase64];
	
	if (doesItemExisit) {
		BOOL result = [AGKeychain modifyKeychainItem:KeyChainItemName
										withItemKind:KeyChainItemKind
										 forUsername:newLogin
									 withNewPassword:[passwdData encodeBase64]];
		if (!result){
			[self displayAlertWithMessageText:@"Nieudana próba modyfikacji danych w Pęku kluczy"];
			return;
		}
	}
	
	else {
		//usuniecie
		
		BOOL result = [AGKeychain addKeychainItem:KeyChainItemName
									 withItemKind:KeyChainItemKind
									  forUsername:newLogin
									 withPassword:[passwdData encodeBase64]];
		if (!result) {
			[self displayAlertWithMessageText:@"Nieudana próba dodania danych do Pęku kluczy"];
			return;
		}
		
	}

	[self displayAlertWithMessageText:@"Zmodyfikowano dane w Pęku kluczy"];
}

- (NSString*)getPasswordFromKeychainForLogin:(NSString*)searchLogin
{
	NSString *passwordFound = nil;
	BOOL doesItemExisit = [AGKeychain checkForExistanceOfKeychainItem:KeyChainItemName
														 withItemKind:KeyChainItemKind
														  forUsername:searchLogin];
	if (doesItemExisit) {
		passwordFound = [AGKeychain getPasswordFromKeychainItem:KeyChainItemName 
												   withItemKind:KeyChainItemKind
													forUsername:searchLogin];
		//return passwordFound;
	} else{
		[[AppController shared] displayAlertWithMessageText:@"Pęk kluczy: Brak dostępu"];
		return nil;
	}
	if (passwordFound ==nil){
		[[AppController shared] displayAlertWithMessageText:@"Pęk kluczy: Brak dostępu"];
		//[NSApp presentError:[NSError errorWithDomain:@"Pęk kluczy: Brak hasła" code:1 userInfo:nil]];
		return nil;
	} else {
		return passwordFound;
	}
}
-(void)displayAlertWithMessageText:(NSString *)messageText
{
	NSAlert *alert = [[[NSAlert alloc] init] autorelease];
	[alert addButtonWithTitle:@"Ok"];
	[alert setMessageText:messageText];
	[alert setAlertStyle:NSInformationalAlertStyle];
	[alert beginSheetModalForWindow:[self window] modalDelegate:self didEndSelector:nil contextInfo:nil]; 
}
@end

